<script setup lang="ts">
defineOptions({
  name: "supplyBottle"
});

import { ref, computed, onMounted, onUnmounted, markRaw, getCurrentInstance, provide } from "vue";
import { queryGasBottleList, deleteGasBottle, deleteGasReturnBottle, deleteGasExpiredBottle, importGasBottleData } from "@/api/modules/operation";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { Edit, Delete } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { useTableCloumns, useSearchOption } from "../hooks";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import add from "./add.vue";
import importBottle from "./importBottle.vue";
import { useMessageBox } from "@/hooks/useCommon";
import checkLogs from "@/views/gas/components/checkLogs.vue";

interface Props {
  //  1 在供气瓶  2 返库气瓶  3 过期气瓶
  type: 1 | 2 | 3;
}

const props = withDefaults(defineProps<Props>(), { type: 1 });

provide("bottleType", props.type);

const searchLoading = ref<boolean>(false);
const gap = 88;
const defaultHeight = 606;
const objectModelTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const searchOption = ref<Array<CommonSearch.SearchOption>>(useSearchOption(props.type));
const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>(useTableCloumns(props.type));
const params = ref<any>({});
// 弹框类型 add 新增   edit 编辑
const addType = ref<"add" | "edit">("add");
const bottleId = ref<string>("");
const addDialogTableVisible = ref<boolean>(false);
const importBottleVisible = ref<boolean>(false);
const checkLogsDialogVisible = ref<boolean>(false);

const checkLogsTitle = computed(() => {
  let type = "";
  let title = "";
  switch (props.type) {
    case 1:
      type = "气瓶台账-在供";
      title = "在供气瓶";
      break;
    case 2:
      type = "气瓶台账-返库";
      title = "返库气瓶";
      break;
    case 3:
      type = "气瓶台账-废料";
      title = "过期特气废料";
      break;
  }
  return { type, title };
});

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "编辑",
    auth: "GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_EDITBTN",
    icon: markRaw(Edit),
    click: (scope: any) => edit(scope)
  },
  {
    content: "删除",
    auth: "GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_DELETEBTN",
    icon: markRaw(Delete),
    type: "danger",
    click: (scope: any) => del(scope)
  }
];

let defaultParams: any = {
  // 1：在供，2：返库，3：过期
  lifeCycle: props.type
};
let currentParams: any = {};

const getRowKey = row => {
  return row.id;
};

const sortChangeHandler = ({ column, order }: CommonTable.SortParams) => {
  const { property: orderBy = "" } = column;
  // ascending  descending
  const isAsc = order === "ascending" ? true : order === "descending" ? false : true;
  currentParams["orderBy"] = orderBy;
  currentParams["isAsc"] = isAsc;
  if (!order) {
    currentParams.orderBy && delete currentParams.orderBy;
    currentParams.isAsc && delete currentParams.isAsc;
  }
  updateParams();
};

const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
  const style = {};
  if (columnIndex === 3) {
    style["text-align"] = "center";
  }
  return style;
};

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const resetSearchFormHandler = () => {
  currentParams = {};
  updateParams();
};

const addFn = () => {
  bottleId.value = "";
  addType.value = "add";
  addDialogTableVisible.value = true;
};

const { proxy }: any = getCurrentInstance();

const downloadFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/steelCylinder/downloadTemplate";
  //  状态（1：在供，2：返库，3：过期）
  const { type: cylinderStatus = 1 } = props;
  const params = { cylinderStatus };
  proxy.download("post", url, params);
}, delay);

const batchImportFn = () => {
  importBottleVisible.value = true;
};

const batchExportFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/steelCylinder/exportData";
  const params = commonTableRef.value.getParams();
  proxy.download("post", url, params);
  PxMessageBox.alert("正在导出您筛选的数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "批量导出", {
    confirmButtonText: "我知道了"
  });
}, delay);

const edit = scope => {
  const {
    row: { id = "" }
  } = scope;
  bottleId.value = id;
  addType.value = "edit";
  addDialogTableVisible.value = true;
};

const del = async scope => {
  const {
    row: { cylinderNo: labelName = "", id = "" }
  } = scope;
  const msg = `确定要删除气瓶 ${labelName}吗？`;
  useMessageBox("delete", msg, async () => {
    const params = { labelName, id };
    switch (props.type) {
      case 1:
        await deleteGasBottle(params);
        break;
      case 2:
        await deleteGasReturnBottle(params);
        break;
      case 3:
        await deleteGasExpiredBottle(params);
        break;
    }
    PxMessage.success("删除成功！");
    commonTableRef.value.queryTableData();
  });
};

const checkLogsFn = () => {
  checkLogsDialogVisible.value = true;
};

const submitHandler = (flag: boolean = false) => {
  const message = flag ? "导入成功" : addType.value === "add" ? "创建成功" : "编辑成功";
  PxMessage.success(message);
  commonTableRef.value.queryTableData();
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div v-loading="searchLoading" class="all-orders">
    <div class="all-orders-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        v-model:loading="searchLoading"
        :row-num="6"
        :operationSpan="5"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="resetSearchFormHandler"
      />
    </div>
    <div class="all-orders-btns">
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_ADDBTN'" type="primary" @click="addFn">新增</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_DOWNLOADBTN'" type="primary" plain @click="downloadFn">模板下载</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_IMPORTBTN'" type="primary" plain @click="batchImportFn">批量导入</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_EXPORTBTN'" type="primary" plain @click="batchExportFn">批量导出</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_CHECKLOGS_BTN'" type="primary" plain @click="checkLogsFn">查看日志</px-button>
    </div>
    <div ref="objectModelTableRef" class="all-orders-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :row-key="getRowKey"
        :header-cell-style="headerCellStyleFn"
        :axiosApi="queryGasBottleList"
        :params="params"
        @sort-change="sortChangeHandler"
      />
    </div>
    <add v-if="addDialogTableVisible" :id="bottleId" v-model="addDialogTableVisible" :type="addType" :lifeCycle="type" @submit="submitHandler" />
    <importBottle
      v-if="importBottleVisible"
      v-model="importBottleVisible"
      :uploadApi="importGasBottleData"
      :lifeCycle="type"
      @submit="submitHandler(true)"
    />
    <checkLogs v-if="checkLogsDialogVisible" v-model="checkLogsDialogVisible" :type="checkLogsTitle.type" :title="checkLogsTitle.title" />
  </div>
</template>

<style lang="scss" scoped>
.all-orders {
  width: 100%;
  background-color: #fff;

  .all-orders-search {
    width: 100%;
  }

  .all-orders-btns {
    display: flex;
    align-items: center;
    margin-top: 16px;
  }

  .all-orders-table {
    margin-top: 16px;
  }
}
</style>
